//
//  YJLedgeViewController.m
//  健康饮食
//
//  Created by qianfeng01 on 15/7/4.
//  Copyright (c) 2015年 qianfeng01. All rights reserved.
//

#import "YJLedgeViewController.h"
#import "YJHealthModel.h"
#import "YJHealthCell.h"
#import "AFNetworking.h"
#import "YJinformationViewController.h"
@interface YJLedgeViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    UITableView *_tableView;
    NSMutableArray *_dataArray;
    AFHTTPRequestOperationManager *_manager;
}
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) NSMutableArray *dataArray;
@property (nonatomic,strong) AFHTTPRequestOperationManager *manager;

@end

@implementation YJLedgeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.dataArray=[[NSMutableArray alloc] init];
    NSString *cellName = @"YJHealthCell";
    [self creatTableView:cellName];
    self.tableView.rowHeight=100;
    [self creatHttpRequest];
    self.currentPage=1;
    NSString *url =[NSString stringWithFormat:kUrl,self.currentPage];
    [self loadData:url];
    [self refreshData];
}
-(void)loadData:(NSString *)url{
    
    NSString *path =[YJHelper getFullPathWithFile:url];
    BOOL isExist =[[NSFileManager defaultManager]fileExistsAtPath:path];
    BOOL isTimeout =[YJHelper isTimeOutWithFile:path timeOut:24*60*60];
    if ((isExist==YES)&&(isTimeout==NO)) {
        NSData *data =[NSData dataWithContentsOfFile:[YJHelper getFullPathWithFile:url]];
        if (self.currentPage==1) {
            [self.dataArray removeAllObjects];
    }
        NSDictionary *ledgeDict =[NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        NSDictionary *dicts =ledgeDict[@"data"];
        NSArray *array =dicts[@"nous"];
        for (NSDictionary *dict in array) {
            YJHealthModel *model =[[YJHealthModel alloc] init];
            [model setValuesForKeysWithDictionary:dict];
            [self.dataArray addObject:model];
        }
        [self.tableView reloadData];
        [self endRefreshing];
        return;
    }
    
    __weak typeof(self)weakSelf =self;
    [self.manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (responseObject) {
            if (weakSelf.currentPage==1) {
                [weakSelf.dataArray removeAllObjects];
                NSData *data=(NSData *)responseObject;
                [data writeToFile:[YJHelper getFullPathWithFile:url] atomically:YES];
            }
            NSDictionary *ledgeDict =[NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableContainers) error:nil];
            NSDictionary *dicts =ledgeDict[@"data"];
            NSArray *array =dicts[@"nous"];
            for (NSDictionary *dict in array) {
                YJHealthModel *model =[[YJHealthModel alloc] init];
                [model setValuesForKeysWithDictionary:dict];
                [self.dataArray addObject:model];
            }
           
            [self.tableView reloadData];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
    [self endRefreshing];
}

-(void)refreshData{
    __weak typeof(self) weakSelf =self;
    [self.tableView addRefreshHeaderViewWithAniViewClass:[JHRefreshCommonAniView class] beginRefresh:^{
        if (weakSelf.isRefreshing) {
            return ;
        }
        weakSelf.isRefreshing=YES;
        weakSelf.currentPage =1;
        NSString *url =[NSString stringWithFormat:kUrl,weakSelf.currentPage];
        
        [weakSelf loadData:url];
    }];
    [self.tableView addRefreshFooterViewWithAniViewClass:[JHRefreshCommonAniView class] beginRefresh:^{
        if (weakSelf.isLoadMore) {
            return ;
        }
        weakSelf.isLoadMore =YES;
        weakSelf.currentPage ++;
        NSString *url =[NSString stringWithFormat:kUrl,weakSelf.currentPage];
        [weakSelf loadData:url];
    }];
}

-(void)endRefreshing{
    if (self.isRefreshing) {
        self.isRefreshing = NO;//标记刷新结束
        //正在刷新 就结束刷新
        [self.tableView headerEndRefreshingWithResult:JHRefreshResultNone];
    }
    if (self.isLoadMore) {
        self.isLoadMore = NO;
        [self.tableView footerEndRefreshing];
    }
    
}

#pragma mark -
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    YJHealthCell *cell =[tableView dequeueReusableCellWithIdentifier:@"YJHealthCell" forIndexPath:indexPath];
    YJHealthModel *model =self.dataArray[indexPath.row];
    [cell showDataWithModel:model];
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    YJinformationViewController *controller =[[YJinformationViewController alloc] init];
    YJHealthModel *model = self.dataArray[indexPath.row];
    controller.code =model.code;
    [self.navigationController pushViewController:controller animated:YES];
}
@end
